package handler

import (
	"context"
	"encoding/json"
	"github.com/micro/go-micro/util/log"

	"gitee.com/fanbuchi/mocker/api/client"
	"github.com/micro/go-micro/errors"
	api "github.com/micro/go-micro/api/proto"
	//mocker "path/to/service/proto/mocker"
	mocker "gitee.com/fanbuchi/mocker/srv/proto/mocker"
)

type Mocker struct{}

func extractValue(pair *api.Pair) string {
	if pair == nil {
		return ""
	}
	if len(pair.Values) == 0 {
		return ""
	}
	return pair.Values[0]
}

// Mocker.Call is called by the API as /mocker/call with post body {"name": "foo"}
func (e *Mocker) Call(ctx context.Context, req *api.Request, rsp *api.Response) error {
	log.Log("Received Mocker.Call request api")
	//log.Log("body--->",req.Body)
	//log.Log("post--->",req.Post)
	// extract the client from the context
	mockerClient, ok := client.MockerFromContext(ctx)
	if !ok {
		return errors.InternalServerError("com.xgggh.api.mocker.mocker.call", "mocker client not found")
	}
	// make request
	response, err := mockerClient.Call(ctx, &mocker.Request{
		Name: extractValue(req.Post["name"]),
	})
	if err != nil {
		return errors.InternalServerError("com.xgggh.api.mocker.mocker.call", err.Error())
	}

	b, _ := json.Marshal(response)

	rsp.StatusCode = 200
	rsp.Body = string(b)

	return nil
}
